/* Copyright 2011 Jonathan Komorek
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jkomorek.eurl.selenium;

import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

/**
 *
 * @author Jonathan Komorek
 */
public class ScriptLoader {


    public static Script loadFromClassPath(String classPathLocation) {
        System.out.println("Loading script from ClassPath ["+(classPathLocation)+"]");
        URL scriptURL = Thread.currentThread().getContextClassLoader().getResource(classPathLocation);
        if (scriptURL == null) throw new RuntimeException("Unable to find Script ["+classPathLocation+"] on ClassPath");
        return loadFromURL(scriptURL);
    }
    //fx3Hm9gS3Ph3

    public static Script loadFromURL(URL url) {
        if (url == null) throw new RuntimeException("Cannot load script from null URL");

        String urlString = url.toExternalForm();

        System.out.println("Loading script from URL ["+urlString+"]");

        ScriptBuilder scriptBuilder = new ScriptBuilder();

        HtmlUnitDriver driver = new HtmlUnitDriver();
        driver.get(urlString);

        WebElement webElement = driver.findElementByTagName("title");
        if (webElement == null) throw new RuntimeException("Failed to find title in script ["+urlString+"]");
        System.out.println("Title ["+webElement.getText()+"]");
        scriptBuilder.setTitle(webElement.getText());

        webElement = driver.findElementByTagName("link");
        if (webElement == null) throw new RuntimeException("Failed to find baseURL in script ["+urlString+"]");
        String baseUrl =  webElement.getAttribute("href");
        baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length()-1) : baseUrl;
        System.out.println("BaseURL ["+baseUrl +"]");
        scriptBuilder.setBaseURL(baseUrl);

        webElement = driver.findElementByTagName("tbody");
        if (webElement == null) throw new RuntimeException("Failed to find table in script ["+urlString+"]");

        List<WebElement> steps = webElement.findElements(By.tagName("tr"));
        if (steps == null) throw new RuntimeException("Failed to find any steps in script ["+urlString+"]");
        if (steps.isEmpty() ) throw new RuntimeException("Found zero steps in script ["+urlString+"]");

        List<WebElement> stepRecord;
        String command;
        String target;
        String value;
        for (WebElement step : steps) {
            stepRecord = step.findElements(By.tagName("td"));
            if (stepRecord.size() != 3) throw new RuntimeException("Expected to find 3 cells in step record but found ["+stepRecord.size()+"]");
            command = stepRecord.get(0).getText();
            target = stepRecord.get(1).getText();
            value = stepRecord.get(2).getText();
            System.out.println("["+command+"] ["+target+"] ["+value+"]");
            scriptBuilder.addStep(command, target, value);
        }

        return scriptBuilder.done();
    }

}
